package com.bensonbasement.snorflux.client;

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

public class ImageWarehouse {
	
	private static ImageWarehouse instance = null;
	
	public static ImageWarehouse getInstance() {
		if (instance == null) {
			instance = new ImageWarehouse();
		}
		return instance;
	}
	
	private Map<String,BufferedImage> imageMap;
	
	private ImageWarehouse() {
		imageMap = new HashMap<String,BufferedImage>();
	}
	
	public void loadImage(String name) {
		this.getImage(name);
	}
	
	public BufferedImage getImage(String name) {
		BufferedImage image = imageMap.get(name);
		if (image == null) {
			try {
				FileInputStream stream = new FileInputStream("bin/"+name+".png");
				//InputStream stream = this.getClass().getResourceAsStream("../../../../"+name+".png");
				BufferedImage unconverted = ImageIO.read(stream);

				GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
				GraphicsDevice device = env.getDefaultScreenDevice();
				GraphicsConfiguration config = device.getDefaultConfiguration();
				image = config.createCompatibleImage(unconverted.getWidth(), unconverted.getHeight(), Transparency.BITMASK);
				
				Graphics g = null;
				try {
					g = image.getGraphics();
					g.drawImage(unconverted, 0, 0, null);
				}
				finally {
					g.dispose();
				}
				
			} catch (IOException ex) {
				throw new RuntimeException("Cannot find image: "+name);
			}
			imageMap.put(name, image);
		}
		return image;
	}
}
